import {request} from '@umijs/max';
import * as API from "@/services";
import queryString from 'query-string';
import {ArticlesCitedInfo} from "@/services";
import {createRespResult} from "kf-web-library";


/** 文章 分页检索请求 */
export async function queryFrontArticlesByEs(params: API.FrontArticleEsPageQueryParams): Promise<API.RespPageResult<API.FrontArticle>> {
  return request('/api/v1/front/article/eslist/v2', {
    params,
  });
}

/**
 * 文章图表
 */
export async function queryFrontArticleChartsByEs(params: API.FrontArticleChartsEsPageQueryParams): Promise<API.RespPageResult<API.FrontArticle>> {
  return request('/api/v1/front/article/eslist/figure-table/v2', {
    params,
  });
}

/**
 * 文章视频
 */
export async function queryFrontArticleVideosByEs(params: API.FrontArticleVideoEsPageQueryParams): Promise<API.RespPageResult<API.FrontArticle>> {
  return request('/api/v1/front/article/eslist/video/v2', {
    params,
  });
}


/** 文章 详情请求 */
export async function queryFrontArticle(bizId: API.EntityId, saveFootprint: boolean = false): Promise<API.RespResult<API.FrontArticle>> {
  //兼容DOI:  /api/v1/front/article/10.7507_1672-2531.202303021
  //兼容ID:   /api/v1/front/article/1121
  const articleId = `${bizId}`.startsWith("10.") ? `${bizId}`.replace("/", "_") : bizId;
  return request(`/api/v1/front/article/${articleId}`, {
    params: {
      saveFootprint: saveFootprint ?? undefined,
    }
  });
}

export async function queryFrontArticleCitedBy(articleId: API.EntityId, journalAbbreviation: string): Promise<API.RespResult<API.ArticlesCitedInfo>> {
  //return request(`https://www.tcsurg.org/indexAction!getArticleCitedBy.action`, {
  return request(`/indexAction!getArticleCitedBy.action`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', //设置请求头为 form-urlencoded
    },
    data: queryString.stringify({
      article_id: articleId,
      journalAbbreviation: journalAbbreviation,
      isShowCitedBy: "source:cnki", //知网
    })
  }).then((data) => {
    const infos = JSON.parse(data) as API.ArticlesCitedInfo[];
    const ret = infos.find(info => info.articleId === articleId)
    return createRespResult(ret, true);
  });
}

/** 热文/特文/刊文 分页检索请求 */
export async function queryFrontArticles(params: API.FrontArticlePageQueryParams): Promise<API.RespPageResult<API.FrontArticle>> {
  return request('/api/v1/front/article', {
    params,
  });
}

/**
 * 推荐文章(猜你喜欢)
 * @param params
 */
export async function queryFrontRecommendArticles(params: API.FrontRecommendArticlePageQueryParams): Promise<API.RespPageResult<API.FrontArticle>> {
  return request('/api/v1/front/article/recommend-article', {
    params,
  });
}

/**
 * 下载PDF(权限检查)
 */
export async function preCheckArticleDownload(bizId: API.EntityId, opts?: API.AxiosRequestOpts): Promise<API.RespResult<boolean>> {
  return request(`/api/v1/front/article/${bizId}/pdf/pre-check`, {
     method: "POST",
    ...(opts || {}),
  });
}
